<template>
  <el-cascader
    v-model="selectedValue"
    :options="treeData"
    :props="cascaderProps"
    :placeholder="placeholder"
    :disabled="disabled"
    clearable
    :show-all-levels="false"
    @change="handleChange"
  >
  </el-cascader>
</template>

<script>
export default {
  name: 'DepartmentTreeSelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择部门'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeData: [],
      selectedValue: this.value,
      cascaderProps: {
        value: 'code',
        label: 'name',
        children: 'children',
        checkStrictly: true,
        emitPath: false,
        expandTrigger: 'hover'
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.selectedValue = newVal
      },
      immediate: true
    }
  },
  created() {
    this.fetchDepartmentData()
  },
  methods: {
    // 获取部门数据
    async fetchDepartmentData() {
      try {
        const response = await this.$axios.get('/employee/department')
        if (response && response.result === 200) {
          this.treeData = this.processTreeData(response.data || [])
          
          // 如果有初始值，确保在数据加载完成后能正确显示
          if (this.value) {
            this.$nextTick(() => {
              this.selectedValue = this.value
            })
          }
        } else {
          this.$message.error('获取部门数据失败')
        }
      } catch (error) {
        console.error('获取部门数据出错：', error)
        this.$message.error('获取部门数据失败')
      }
    },

    // 处理树形数据
    processTreeData(data) {
      return data.map(node => {
        const newNode = { ...node }
        if (Array.isArray(newNode.children)) {
          if (newNode.children.length === 0) {
            delete newNode.children
          } else {
            newNode.children = this.processTreeData(newNode.children)
          }
        }
        return newNode
      })
    },

    // 选择值改变时触发
    handleChange(value) {
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style scoped>
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader-node__label) {
  display: flex;
  align-items: center;
}

:deep(.el-cascader-node__postfix) {
  top: 50%;
  transform: translateY(-50%);
}

:deep(.el-cascader__label) {
  width: 100%;
}

/* 所有节点都可以点击 */
:deep(.el-cascader-node) {
  cursor: pointer;
}

:deep(.el-cascader-node.in-active-path) {
  color: #409EFF;
  font-weight: bold;
}
</style> 